package app

import (
	"gitee.com/zmhfly8/gm/pkg/errcode"
	"github.com/Gre-Z/common/jtime"
	"github.com/gin-gonic/gin"
	"net/http"
	"time"
)

type Response struct {
	Ctx *gin.Context
}
type WxResult struct {
	Code    string `json:"code"`
	Message string `json:"message"`
}
type Result struct {
	Errno    int    `json:"errno"`
	Error    string `json:"error"`
	DataType string `json:"dataType"`
	Data     any    `json:"data"`
	Time     jtime.JsonTime
}
type Paging struct {
	First      int   `json:"first"`
	Before     int   `json:"before"`
	Current    int   `json:"current"`
	Last       int   `json:"last"`
	Next       int   `json:"next"`
	Limit      int   `json:"limit"`
	TotalPages int   `json:"totalPages"`
	TotalItems int64 `json:"totalItems"`
}

func NewResponse(ctx *gin.Context) *Response {
	return &Response{Ctx: ctx}
}
func (r *Response) Ok() {
	r.Ctx.JSON(http.StatusOK, Result{
		Errno:    0,
		Error:    "请求成功",
		DataType: "OBJECT",
		Data:     gin.H{},
		Time: jtime.JsonTime{
			Time: time.Now(),
		},
	})
}
func (r *Response) WxOk() {
	r.Ctx.JSON(http.StatusOK, WxResult{
		Code:    "SUCCESS",
		Message: "",
	})
}
func (r *Response) WxError(msg string) {
	r.Ctx.JSON(http.StatusInternalServerError, WxResult{
		Code:    "FAIL",
		Message: msg,
	})
}
func (r *Response) Success(data interface{}) {
	if data == nil {
		data = gin.H{}
	}

	r.Ctx.JSON(http.StatusOK, Result{
		Errno:    0,
		Error:    "请求成功",
		DataType: "OBJECT",
		Data:     data,
		Time: jtime.JsonTime{
			Time: time.Now(),
		},
	})
}

func (r *Response) ToList(list interface{}) {
	r.Ctx.JSON(http.StatusOK, Result{
		Errno:    0,
		Error:    "请求成功",
		DataType: "LIST",
		Data: gin.H{
			"body": list,
		},
		Time: jtime.JsonTime{
			Time: time.Now(),
		},
	})

}
func (r *Response) ToPaging(list interface{}, p Page, totalRows int64) {
	r.Ctx.JSON(http.StatusOK, Result{
		Errno:    0,
		Error:    "请求成功",
		DataType: "PAGING",
		Data: gin.H{
			"body":   list,
			"paging": GetPaging(p, totalRows),
		},
		Time: jtime.JsonTime{
			Time: time.Now(),
		},
	})

}
func (r *Response) ToError(err *errcode.Error) {
	r.Ctx.JSON(http.StatusOK, Result{
		Errno:    err.Code(),
		Error:    err.Msg(),
		DataType: "error",
		Data:     nil,
		Time: jtime.JsonTime{
			Time: time.Now(),
		},
	})
}
